package com.kaibes.imserver.model.utils;

import java.io.File;
import java.util.HashMap;
import java.util.Set;

import com.kaibes.imserver.model.data.KaibesFile;

public class KaibesFilesUtil {

	private int maxFile;
	private HashMap<String, KaibesFile> kaibesFiles;
	
	public KaibesFilesUtil(int maxFile) {
		this.maxFile = maxFile;
		this.kaibesFiles = new HashMap<String, KaibesFile>();
	}
	
	public KaibesFile addKabesFile(KaibesFile kaibesFile) {
		if (getKaibesFiles().size() < getMaxFile()) {
			getKaibesFiles().put(kaibesFile.getName(), kaibesFile);
			return kaibesFile;
		} else {
			return null;
		}
	}
	
	public boolean hasKaibesFile(String filename){
		return getKaibesFiles().containsKey(filename);
	}
	
	public void clean(){
		Set<String> keys = getKaibesFiles().keySet();
		String[] keysStr = new String[keys.size()];
		keys.toArray(keysStr);
		for (int i = 0; i < keysStr.length; i++) {
			removeKaibesFile(keysStr[i]);
		}
	}
	
	public void removeKaibesFile(String filename){
		getKaibesFiles().get(filename).close();
		getKaibesFiles().remove(filename);
	}
	
	public void removeKaibesFileNotClose(String filename){
		getKaibesFiles().remove(filename);
	}
	
	public KaibesFile getKaibesFile(String filename){
		return getKaibesFiles().get(filename);
	}

	private int getMaxFile() {
		return maxFile;
	}

	public void setMaxFile(int maxFile) {
		this.maxFile = maxFile;
	}

	private HashMap<String, KaibesFile> getKaibesFiles() {
		return kaibesFiles;
	}
	
	public void cacheRenameToFile(KaibesFile cacheFile) {
		cacheFile.close();
		File file = new File(cacheFile.getAbsolutePath().replace("cache", "files"));
		cacheFile.renameTo(file);
	}

}
